import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

// 解决Vue-Router重复导航到同一路由报错的问题
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') throw err
  })
}

// 路由懒加载
const Login = () => import('@/views/login/index')
const Register = () => import('@/views/register/index')
const Layout = () => import('@/layout/index')

// 管理员路由
const adminRoutes = [
  {
    path: '/admin',
    component: Layout,
    redirect: '/admin/dashboard',
    meta: { title: '管理员', role: ['admin'] },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/admin/dashboard/index'),
        meta: { title: '仪表盘', icon: 'dashboard' }
      },
      {
        path: 'product',
        name: 'Product',
        component: () => import('@/views/admin/product/index'),
        meta: { title: '商品管理', icon: 'shopping' }
      },
      {
        path: 'category',
        name: 'Category',
        component: () => import('@/views/admin/category/index'),
        meta: { title: '分类管理', icon: 'menu' }
      },
      {
        path: 'leader',
        name: 'Leader',
        component: () => import('@/views/admin/leader/index'),
        meta: { title: '团长管理', icon: 'user' }
      },
      {
        path: 'order',
        name: 'Order',
        component: () => import('@/views/admin/order/index'),
        meta: { title: '订单管理', icon: 'order' }
      },
      {
        path: 'commission',
        name: 'Commission',
        component: () => import('@/views/admin/commission/index'),
        meta: { title: '佣金管理', icon: 'money' }
      },
      {
        path: 'delivery-route',
        name: 'DeliveryRoute',
        component: () => import('@/views/admin/delivery-route/index'),
        meta: { title: '配送路线', icon: 'route' }
      }
    ]
  }
]

// 团长路由
const leaderRoutes = [
  {
    path: '/leader',
    component: Layout,
    redirect: '/leader/dashboard',
    meta: { title: '团长', role: ['leader'] },
    children: [
      {
        path: 'dashboard',
        name: 'LeaderDashboard',
        component: () => import('@/views/leader/dashboard/index'),
        meta: { title: '仪表盘', icon: 'dashboard' }
      },
      {
        path: 'order',
        name: 'LeaderOrder',
        component: () => import('@/views/leader/order/index'),
        meta: { title: '订单管理', icon: 'order' }
      },
      {
        path: 'commission',
        name: 'LeaderCommission',
        component: () => import('@/views/leader/commission/index'),
        meta: { title: '我的佣金', icon: 'money' }
      },
      {
        path: 'delivery',
        name: 'LeaderDelivery',
        component: () => import('@/views/leader/delivery/index'),
        meta: { title: '配送信息', icon: 'route' }
      }
    ]
  }
]

// 公共路由
const constantRoutes = [
  {
    path: '/login',
    component: Login,
    hidden: true
  },
  {
    path: '/register',
    component: Register,
    hidden: true
  },
  {
    path: '/',
    redirect: '/login',
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/error/404'),
    hidden: true
  }
]

// 404路由应该在所有路由之后
const notFoundRoute = [
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

const createRouter = () => new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

// 根据角色动态添加路由
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const role = localStorage.getItem('role')
  
  // 判断是否已登录
  if (token) {
    // 如果已登录且访问登录页，则重定向到首页
    if (to.path === '/login' || to.path === '/register' || to.path === '/') {
      // 检查角色是否有效
      if (role === 'admin') {
        next({ path: '/admin/dashboard' })
      } else if (role === 'leader') {
        next({ path: '/leader/dashboard' })
      } else {
        // 角色无效，清除token并重定向到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('role')
        next('/login')
      }
    } else {
      // 检查路由是否已添加
      const hasRoutes = router.options.routes.length > constantRoutes.length
      
      // 如果路由已添加或目标路径是404页面，直接放行
      if (hasRoutes || to.path === '/404') {
        next()
      } else {
        // 根据角色添加路由
        let routes = []
        if (role === 'admin') {
          routes = adminRoutes
        } else if (role === 'leader') {
          routes = leaderRoutes
        } else {
          // 角色无效，清除token并重定向到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('role')
          next('/login')
          return
        }
        
        // 动态添加路由
        router.addRoutes([...routes, ...notFoundRoute])
        router.options.routes = [...constantRoutes, ...routes, ...notFoundRoute]
        
        // 继续路由，使用replace避免导航重复
        next({ ...to, replace: true })
      }
    }
  } else {
    // 未登录，如果访问需要登录的页面则跳转到登录页
    if (to.path === '/login' || to.path === '/register' || to.path === '/' || to.path === '/404') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router 